package com.xinzhi.savingpot.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.junit.Test;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;

public class jwtUtil {
    public static String TOKEN_SECRET = "houhou";  //密钥
    public static long EXPIRE_TIME = 24*60*60*1000;  //过期时间一天

    @Test
    public void create() {
        Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
        String username = "卷毛";
        String userage = "18";
        try {
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);  //算法对象
            //设置头信息
            HashMap<String, Object> heard = new HashMap<String, Object>();
            heard.put("typ", "JWT"); //加密类型是JWT
            heard.put("alg", "HS256"); //算法是HS256
            String token = JWT.create()
                    .withHeader(heard)  //jwt添加header
                    .withClaim("loginName", username) //声明username
                    .withClaim("userage", userage)   //声明userage
                    .withExpiresAt(date)  //设置过期时间
                    .sign(algorithm);  //签名
            System.out.println(token);

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
    @Test
    public void verify(){
        try {
            Algorithm algorithm  = Algorithm.HMAC256(TOKEN_SECRET); //算法对象
            JWTVerifier verifier = JWT.require(algorithm).build(); // JWT验证器
            DecodedJWT jwt = verifier.verify("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJsb2dpbk5hbWUiOiLljbfmr5siLCJleHAiOjE2MDc2OTMzMTAsInVzZXJhZ2UiOiIxOCJ9.WT2UpWQ0nbiaxTGQkF2tLQpdvnhy19IAjfS1IQcqDOg");
            System.out.println(jwt.getHeader());
            System.out.println(jwt.getPayload());
            System.out.println(jwt.getSignature());
            System.out.println(jwt.getToken());
            //header 中的元素用getHeaderClaim()获取
            System.out.println(jwt.getHeaderClaim("typ").asString());  //header中的typ
            System.out.println(jwt.getHeaderClaim("alg").asString());  //header中的alg
            //payload中的元素有两种写法
            //getClaim("loginName")
            //getClaims().get("loginName")
            System.out.println(jwt.getClaim("loginName").asString()); //用户名
            System.out.println(jwt.getClaims().get("userage").asString()); //年龄

            System.out.println(jwt.getExpiresAt()); //失效时间(到期时间)
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
}
